package com.chenfan.process.entity.po;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableName;
import com.chenfan.ccp.entity.BaseEntity;
import com.chenfan.ccp.plug.mybatis.annotation.Column;
import com.chenfan.ccp.util.tool.UuidUtil;
import com.chenfan.infra.context.UserContextHolder;
import com.chenfan.process.entity.dto.ApprovalTemplateReceivedDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author K
 * @date 2021/2/25
 */
@EqualsAndHashCode(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@TableName(value = "process_approval_template_snapshot")
public class ApprovalTemplateSnapshotPo extends BaseEntity<ApprovalTemplateSnapshotPo> {

    public static final String APPROVAL_TEMPLATE_ID = "approval_template_id";

    @Column(commit = "快照内容", length = -1)
    private String content;

    @ApiModelProperty("审批模板ID")
    private Long approvalTemplateId;

    @ApiModelProperty("表单ID")
    private Long formId;

    @ApiModelProperty("版本")
    private Long version;

    @Column(commit = "创建人")
    private Long createBy;

    @Column(commit = "创建人名称")
    private String createName;

    @Column(commit = "更新人")
    private Long updateBy;

    @Column(commit = "更新人名称")
    private String updateName;

    private String approvalName;

    public static ApprovalTemplateSnapshotPo of(ApprovalTemplateReceivedDTO template, ApprovalTemplatePo templatePo) {
        ApprovalTemplateSnapshotPo build = ApprovalTemplateSnapshotPo.builder()
            .content(template.getProcessData().replace("\\n", "")).createBy(UserContextHolder.getUserVo().getUserId())
            .formId(template.getFormId()).createName(UserContextHolder.getUserVo().getRealName()).build();
        build.setId(UuidUtil.generateId());
        build.setApprovalTemplateId(templatePo.getId());
        build.setVersion(templatePo.getVersion());
        return build;
    }

    public void extractFromProcess(List<ProcessPo> processList) {
        // 过滤出空数据, 过滤指定人员
        List<String> approvalName = processList.stream().filter(e -> !e.approvalName())
            .map(ProcessPo::getAssociateGroupName).distinct().collect(Collectors.toList());
        setApprovalName(JSONObject.toJSONString(approvalName));
    }

    public ApprovalTemplateSnapshotPo copy() {
        ApprovalTemplateSnapshotPo approvalTemplateSnapshot = new ApprovalTemplateSnapshotPo();
        BeanUtils.copyProperties(this, approvalTemplateSnapshot);
        return approvalTemplateSnapshot;
    }
}
